//
//  Entry.m
//  WhoPaidfor
//
//  Created by user on 9/26/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "Entry.h"
#import "SBJsonParser.h"
@implementation Entry
#define SERVER_URL @"http://nghexaydung.com/whopaid/public/"
static Entry *_instance = nil;  // <-- important 
@synthesize _id, _user_id, _event_id, _enpenses_type_id, _amount, _description; 
+(Entry *)instance
{ 
	// skip everything
	if(_instance) return _instance; 
    
	// Singleton
	@synchronized([Entry class]) 
	{
		if(!_instance)
		{
			_instance = [[self alloc] init];
            
            //	NSLog(@"Creating global instance!"); <-- You should see this once only in your program
		}
        
		return _instance;
	}
    
	return nil;
}
-(NSMutableArray *)getDatasWS:(int)event_id
{
    NSMutableArray *listData = [[NSMutableArray alloc] init ];
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    //Helper *helper = [Helper instance];
    NSString *url = [NSString stringWithFormat:@"%@/expenses/getlistbyevent?event_id=%d", SERVER_URL, event_id]; 
    NSLog(@" get list entries %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSArray *results = [parser objectWithString:json_string error:nil];
    for (NSDictionary *obj in results)
    {
        BookingClass *booking = [[BookingClass alloc] init];
        booking.bookingId = [[obj objectForKey:@"id"] intValue];
        booking.userId = [[obj objectForKey:@"user_id"] intValue];
        booking.bookingTitle = [obj objectForKey:@"description"];
        booking.picture = [obj objectForKey:@"avatar"];
        booking.idString = [obj objectForKey:@"facebookid"];
        booking.email = [obj objectForKey:@"email"];
        booking.bookingDate = [obj objectForKey:@"created"];
        booking.bookingPrice = [[obj objectForKey:@"totalamount"] doubleValue];
        booking.bookingQuantity = [[obj objectForKey:@"totalpeople"] intValue];
        [listData addObject:booking];
    }
    return listData;
}

-(BookingClass *) getDetailWS:(int)entry_id
{
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSString *url = [NSString stringWithFormat:@"%@/expenses/getexpenseinfo?expenses_id=%d",SERVER_URL, entry_id];
    NSLog(@"get booking detail: %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSDictionary *obj = [parser objectWithString:json_string error:nil];
    BookingClass *booking = [[BookingClass alloc] init];
    booking.bookingId = [[obj objectForKey:@"id"] intValue];
    booking.userId = [[obj objectForKey:@"user_id"] intValue];
    booking.bookingTitle = [obj objectForKey:@"description"];
    booking.bookingDate = [obj objectForKey:@"date_expenses"];
    booking.bookingPrice = [[obj objectForKey:@"amount"] doubleValue];
    booking.email = [obj objectForKey:@"email"];
    booking.picture = [obj objectForKey:@"avatar"];
    booking.userName = [obj objectForKey:@"user_name"];
    booking.idString = [obj objectForKey:@"facebookid"];
    NSArray *pars = [obj objectForKey:@"participants"];
    NSMutableArray *arrUsers = [[NSMutableArray alloc] init];
    for (NSDictionary *obj in pars)
    {
        ParticipateClass *p = [[ParticipateClass alloc] init];
        p.quantity = [[obj objectForKey:@"quantity" ] intValue];
        p.name = [obj objectForKey:@"username"];
        p.image =[obj objectForKey:@"avatar"];
        p.firstMail =[obj objectForKey:@"email"];
        p.userId = [[obj objectForKey:@"user_id"] intValue];
        [arrUsers addObject:p];
        [p release];
    }
    booking.participants = arrUsers;
    return booking;
}


-(int) addEntryWS:(int)user_id Amount:(NSString *)amount Description:(NSString *)description DateExpenses:(NSString *)date_expense eventId:(int)event_id paidFor:(int)paidFor ParticipantStr:(NSString *)parStr
{
    Helper *helper = [Helper instance];
    description = [description stringByReplacingOccurrencesOfString:@" "
                                           withString:@"%20"];
    amount = [helper moneyToString:amount];
    NSString *url = [NSString stringWithFormat:@"id=%d&event_id=%d&user_id=%d&description=%@&member=%@&date=%@&amount=%@&paid_id=%d", 0, event_id, user_id, description, parStr, date_expense, amount, paidFor];
    url = [NSString stringWithFormat:@"%@/expenses/add?%@",SERVER_URL,url];
    NSLog(@"save entry: %@", url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    return 1;
}

-(void)updateEntryWS:(NSInteger)entry_id UserId:(int)user_id Amount:(NSString*)amount Description:(NSString*)description DateExpenses:(NSString *)date_expense eventId:(int)event_id paidFor:(NSInteger)paidFor ParticipantStr:(NSString *)parStr
{
    Helper *helper = [Helper instance];
    description = [description stringByReplacingOccurrencesOfString:@" "
                                                         withString:@"%20"];
    amount = [helper moneyToString:amount];
    NSString *url = [NSString stringWithFormat:@"id=%d&event_id=%d&user_id=%d&description=%@&member=%@&date=%@&amount=%@&paid_id=%d", entry_id, event_id, user_id, description, parStr, date_expense, amount, paidFor];
    url = [NSString stringWithFormat:@"%@/expenses/add?%@",SERVER_URL,url];
    NSLog(@"update entry: %@", url);
    //NSString *contents = [NSString stringWithContentsOfURL:[NSURL URLWithString:url]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

-(void) deleteEntryWS:(NSInteger)entry_id userId:(NSInteger)user_id
{
    NSString *url = [NSString stringWithFormat:@"%@expenses/remove?id=%d&user_id=%d",SERVER_URL,entry_id,user_id];
    NSLog(@"link delete entry %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
-(void) deleteListEntry:(NSString *)entry_ids userId:(NSInteger)user_id
{
    NSString *url = [NSString stringWithFormat:@"%@expenses/removes?id=%@&user_id=%d",SERVER_URL,entry_ids,user_id];
    NSLog(@"link delete entries %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
@end
